package com.rj.data.job;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程处理任务
 */
public abstract class MultiThreadJob<T> {

    ExecutorService pool = Executors.newFixedThreadPool(46);
    protected ListeningExecutorService executorService = MoreExecutors.listeningDecorator(pool);

    /**
     * 定义任务
     * @return
     */
    public abstract List<ListenableFuture<T>> defineJob();

    public Map<Integer, Integer[]> doTask() throws IOException {

        final ListenableFuture<List<T>> resultsFuture = Futures.successfulAsList(defineJob());
        try {
            // block until all tasks are done
            resultsFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
            pool.shutdown();
        } finally {
            pool.shutdown();//重点就是这行
        }


        return null;
    }


}
